# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

# library(ropls)
library(plyr)
library(dplyr)
library(tidyr)
library(tibble)
library(magrittr)
library(ropls)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

data <- read.csv(opt$i, header = T, check.names = F, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    gather("SampleID", "Value", - Metabolite) %>%
    spread(Metabolite, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID"))

classNotes <- unique(sampleInfo$ClassNote)
cn <- combn(classNotes, 2)
for (i in 1 : ncol(cn)) {
    load("oplsda.RData")

    perMN <- plsdaRs@suppLs$permMN %>%
        as.data.frame() %>%
        set_colnames(c("R2X", "R2Y", "Q2", "RMSEE", "pre", "ort", "Similarity")) %>%
        select(- c("pre", "ort")) %>%
        arrange(Similarity)
    parent <- paste0("Model_Validation")
    createWhenNoExist(parent)
    perFileName <- paste0(parent, "/OPLSDA_Permutation.csv")
    write.csv(perMN, perFileName)
}



